//
//  IssueController.m
//  吃货·上海
//
//  Created by 濮亚军 on 15/11/26.
//  Copyright © 2015年 濮亚军. All rights reserved.
//

#import "IssueController.h"

#import <BmobSDK/Bmob.h>
#import <BmobSDK/BmobProFile.h>
#import "MainController.h"
@interface IssueController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property(nonatomic, strong)BmobObject *UserPush;


@end

@implementation IssueController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64);
    self.view.backgroundColor = kBarColor;
    
    self.issueView = [[IssueView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, self.view.frame.size.height - 64)];
    [self.issueView.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_issueView];
    
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageTapAction:)];
    [self.issueView.issueImageView addGestureRecognizer:imageTap];
    
    
}
-(void)imageTapAction:(UITapGestureRecognizer *)imageTap
{
    [self pickImageFromAlbum];
}
-(void)buttonAction:(UIButton *)button
{
    if (![BmobUser getCurrentUser])
    {
        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"请先登录"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alterView show];
    }
    else
    {
        if (self.issueView.issueImageView.image == NULL)
        {
            
            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"照片不能不能为空"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alterView show];
        }
        else
        {
            //上传图片
            [self updataImage];
        }
    }
    
}
- (void)pickImageFromAlbum
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        //NSLog(@"打开相册成功");
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //  是否允许编辑
        picker.allowsEditing = YES;
        //  设置代理，自动去调用代理方法
        //  需要遵守UINavigationControllerDelegate和UIImagePickerControllerDelegate协议
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        NSLog(@"打开相册失败");
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"ok");
    //  1.将选中的图片赋值给imageView
    //  通过字典的key值来取出对应的value值，value就是选中的图片
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //  将某一张图片存到相册中
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    CGSize imageSize = image.size;
    imageSize.height = 256;
    imageSize.width = 256;
    image = [self imageWithImage:image scaledToSize:imageSize];
    //给上传图片区域附上图片
    self.issueView.issueImageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.issueView.iconImageView.image = NULL;
    //获取时间来命名图片
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    self.nowTime = [NSString stringWithFormat:@"%f", a];
    NSLog(@"nowTime ==== %@", self.nowTime);
    [self saveImage:image WithName:[self.nowTime stringByAppendingString:@".jpg"]];
    
    //  2.将本界面模态回去，即dismiss
    [self dismissViewControllerAnimated:YES completion:nil];
}
//压缩图片封装方法
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}
- (NSString *)documentFolderPath
{
    NSLog(@"documentFolderPath ==== %@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}
-(void)updataImage
{
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.jpg",[self documentFolderPath], self.nowTime];
    NSLog(@"filePath ==== %@", filePath);
    [BmobProFile uploadFileWithPath:filePath block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url,BmobFile *bmobFile) {
        if (isSuccessful) {
            //上传成功后返回文件名及url
            NSLog(@"filename:%@",filename);
            NSLog(@"url:%@",url);
            NSLog(@"bmobFile:%@\n",bmobFile);
            BmobUser *bUser = [BmobUser getCurrentUser];
            BmobFile *iconFile = [bUser objectForKey:@"icon"];
            BmobObject *UserPush = [BmobObject objectWithClassName:@"UserPush"];
            [UserPush setObject:bmobFile forKey:@"photo"];
            [UserPush setObject:self.issueView.textField.text forKey:@"info"];
            [UserPush setObject:bUser.username forKey:@"username"];
            [UserPush setObject:iconFile forKey:@"userIcon"];
            [UserPush saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful)
                {
                    self.issueView.textField.text = NULL;
                    self.issueView.issueImageView.image = NULL;
                    self.issueView.iconImageView.image = [UIImage imageNamed:@"addImage"];
                    UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"上传成功"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alterView show];
                    BmobObject *userCollection = [BmobObject objectWithClassName:[NSString stringWithFormat:@"Collection%@%@",[UserPush objectForKey:@"username"], [UserPush objectId]]];
                    NSLog(@"%@", [NSString stringWithFormat:@"Collection%@%@",[UserPush objectForKey:@"username"], [UserPush objectId]]);
                    [userCollection saveInBackground];
                    
                    BmobObject *userComment = [BmobObject objectWithClassName:[NSString stringWithFormat:@"userComment%@%@",[UserPush objectForKey:@"username"], [UserPush objectId]]];
                    [userComment saveInBackground];

                }
                else if(error)
                {
                    NSLog(@"error === %@", error);
                    UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"图片上传失败"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alterView show];
                }
            }];
        } else{
            if(error){
                NSLog(@"error%@",error);
                UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"图片上传失败"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alterView show];
            }
        }
    } progress:^(CGFloat progress) {
        //上传进度，此处可编写进度条逻辑
        NSLog(@"progress %f",progress);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
